<script lang="ts" setup>
import { onBeforeMount, ref } from 'vue';
import * as service from '@/service/api/menu';
import { isSuccess } from '@/utils/response';

const modelValue = defineModel<string[]>('value', { required: true });

const menuMap = new Map();
const data = ref([]);
const checked = ref<string[]>([]);

function onSelect(e: string[]) {
  const privileges = new Set<string>();
  for (const id of e) {
    if (menuMap.has(id)) {
      const menu = menuMap.get(id);
      if (menu.type !== 'Folder') {
        const privilegeList = menuMap.get(id).privileges;
        if (privilegeList) {
          privilegeList.forEach((p: string) => privileges.add(p));
        }
      }
    }
  }
  modelValue.value = Array.from(privileges.values());
}

onBeforeMount(async () => {
  const response = await service.tree({ filter: true });
  if (isSuccess(response)) {
    const tree = response.data;
    // 菜单tree转为map
    tree.forEach((element: any) => {
      convertToMap(element);
    });
    // 设置已选择的菜单
    if (modelValue.value && modelValue.value.length > 0) {
      initSelectMenu();
    }
    data.value = tree;
  }
});

function initSelectMenu() {
  const set = new Set(modelValue.value);
  if (set.size > 0) {
    menuMap.forEach((menu, id) => {
      if (menu.type !== 'Folder') {
        if (menu.privileges && menu.privileges.length > 0) {
          menu.privileges.forEach((p: string) => {
            if (set.has(p)) {
              checked.value.push(id);
            }
          });
        }
      }
    });
  }
}

function convertToMap(element: any) {
  menuMap.set(element.id, element);
  if (element.children && element.children.length > 0) {
    element.children.forEach((m: any) => {
      convertToMap(m);
    });
  }
}
</script>

<template>
  <n-tree
    :default-checked-keys="checked"
    :on-update:checked-keys="onSelect"
    label-field="name"
    key-field="id"
    :data="data"
    expand-on-click
    checkable
    multiple
    cascade
  />
</template>
